package com.ztc.ZtcWithdrawalsApply.web;

import com.aqgj.SysArea.bean.SysArea;
import com.aqgj.SysArea.service.SysAreaManager;
import com.aqgj.User.bean.User;
import com.aqgj.User.service.UserManager;
import com.aqgj.util.JsonWrapper;
import com.ztc.AppUser.bean.AppUser;
import com.ztc.AppUser.service.AppUserManager;
import com.ztc.ZtcTransport.bean.ZtcTransport;
import com.ztc.ZtcTransport.service.ZtcTransportManager;
import com.ztc.ZtcTransportCapitalLog.bean.ZtcTransportCapitalLog;
import com.ztc.ZtcTransportCapitalLog.service.ZtcTransportCapitalLogManager;
import com.ztc.ZtcWallet.bean.ZtcWallet;
import com.ztc.ZtcWallet.service.ZtcWalletManager;
import com.ztc.ZtcWalletLog.bean.ZtcWalletLog;
import com.ztc.ZtcWalletLog.dao.ZtcWalletLogDao;
import com.ztc.ZtcWalletLog.service.ZtcWalletLogManager;
import com.ztc.ZtcWithdrawalsApply.bean.ZtcWithdrawalsApply;
import com.ztc.ZtcWithdrawalsApply.service.ZtcWithdrawalsApplyManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Controller
@RequestMapping("ztc/transportCash")
public class ZtcWithdrawalsApplyAction {

    @Autowired
    private ZtcWithdrawalsApplyManager ztcWithdrawalsApplyManager;
    @Autowired
    private ZtcWalletManager ztcWalletManager;
    @Autowired
    private ZtcTransportManager ztcTransportManager;
    @Autowired
    private AppUserManager appUserManager;
    @Autowired
    private SysAreaManager sysAreaManager;
    @Autowired
    private ZtcTransportCapitalLogManager ztcTransportCapitalLogManager;
    @Autowired
    private ZtcWalletLogManager ztcWalletLogManager;
    @Autowired
    private UserManager userManager;

    /**
     * 当前公司提交提现申请.
     * @param  money   金额
     * @return
     */
    @PostMapping("withdrawals")
    @ResponseBody
    public HashMap<String, Object> withdrawals(HttpSession session, String money,Integer accountType,String transferAccount){
        User user=(User)session.getAttribute("userInfo");
        money=new BigDecimal(money).toPlainString();
        BigDecimal money1=new BigDecimal(money);
        if(money1.compareTo(BigDecimal.ZERO)!=1){
            return JsonWrapper.failureWrapperMsg("提现金额不能小于0元！");
        }
        String [] temp=money.split("\\.");
        if(temp.length>1){
            if(temp[1].toString().length()>2){
                return JsonWrapper.failureWrapperMsg("提现金额仅支持两位小数(如:56.88)！");
            }
        }
        ZtcTransport ztcTransport=ztcTransportManager.get(user.getTransportId());
        if(ztcTransport==null){
            return JsonWrapper.failureWrapperMsg("未查询到公司信息，提现申请失败！");
        }
        ZtcWallet ztcWallet=ztcWalletManager.findUserWallet(ztcTransport.getId());
        if(ztcWallet==null){
            return JsonWrapper.failureWrapperMsg("未查询到公司账户信息！");
        }
        if(ztcWallet.getTmoney().compareTo(money1)==-1){
            return JsonWrapper.failureWrapperMsg("提现金额不能超过可提现余额！");
        }
        if(accountType!=1&&accountType!=2){
            return JsonWrapper.failureWrapperMsg("提现申请账户类型错误！");
        }
        return  ztcWithdrawalsApplyManager.withdrawals(ztcWallet,money1,ztcTransport.getId(),accountType,transferAccount);
    }

    /**
     * 管理员提现处理.
     * @param id 提现ID
     * @param status 处理结果 2-完成;3-失败
     * @param remark 提现失败描述
     * @return
     */
    @PostMapping("handleWithdrawals")
    @ResponseBody
    @Transactional
    public HashMap<String, Object> handleWithdrawals(String id, HttpSession session,Integer status,String remark){
        User user=(User)session.getAttribute("userInfo");
        ZtcWithdrawalsApply ztcWithdrawalsApply = ztcWithdrawalsApplyManager.get(id);
        if(ztcWithdrawalsApply == null){
            return JsonWrapper.failureWrapperMsg("提现处理失败，记录不存在！");
        }
        if(status!=2&&status!=3){
            return JsonWrapper.failureWrapperMsg("提现处理失败，参数异常！");
        }
        ztcWithdrawalsApply.setHandleTime(new Date());
        ztcWithdrawalsApply.setStatus(status);
        ztcWithdrawalsApply.setFkHandlePerson(user.getId());
        if(status==3){
            ztcWithdrawalsApply.setFailureDescription(remark);
        }
        ztcWithdrawalsApplyManager.saveWithdrawalsApply(ztcWithdrawalsApply);
        if(ztcWithdrawalsApply.getStatus()==2){
            return JsonWrapper.successWrapper("提现处理成功！");
        }
        //提现失败钱要加回余额
        if(ztcWithdrawalsApply.getStatus()==3){
            ZtcWallet ztcWallet=ztcWalletManager.findUserWallet(ztcWithdrawalsApply.getBusinessId());
            if(ztcWallet==null){
                return JsonWrapper.failureWrapperMsg("网络错误，请稍后重试！");
            }
            BigDecimal bigDecimal=ztcWallet.getMoney().add(ztcWithdrawalsApply.getMoney());
            BigDecimal bigDecimal2=ztcWallet.getTmoney().add(ztcWithdrawalsApply.getMoney());//可提现金额
            ztcWallet.setMoney(bigDecimal);
            ztcWallet.setTmoney(bigDecimal2);
            ztcWalletManager.update(ztcWallet);
            if(ztcWithdrawalsApply.getBusinessType()==1){
                ZtcWalletLog ztcWalletLog=new ZtcWalletLog();
                ztcWalletLog.setAddTime(System.currentTimeMillis());
                ztcWalletLog.setMoney(ztcWithdrawalsApply.getMoney());
                ztcWalletLog.setAfterBalance(bigDecimal);
                ztcWalletLog.setFkOrderId(ztcWithdrawalsApply.getId());
                ztcWalletLog.setFkUserId(ztcWithdrawalsApply.getBusinessId());
                ztcWalletLog.setType(13);
                ztcWalletLog.setComment("提现失败入账");
                ztcWalletLogManager.save(ztcWalletLog);
            }else{
                ZtcTransportCapitalLog ztcTransportCapitalLog =new ZtcTransportCapitalLog();
                ztcTransportCapitalLog.setBusinessId(ztcWithdrawalsApply.getId());
                ZtcTransport transport = new ZtcTransport();
                transport.setId(ztcWithdrawalsApply.getBusinessId());
                ztcTransportCapitalLog.setZtcTransport(transport);
                //ztcTransportCapitalLog.setTransportId(ztcWithdrawalsApply.getBusinessId());
                ztcTransportCapitalLog.setAfterBalance(bigDecimal);
                ztcTransportCapitalLog.setCreateTime(new Date());
                ztcTransportCapitalLog.setType("2");
                ztcTransportCapitalLog.setMoney(ztcWithdrawalsApply.getMoney());
                ztcTransportCapitalLog.setRemark("提现失败入账");
                ztcTransportCapitalLogManager.save(ztcTransportCapitalLog);
            }
            return JsonWrapper.successWrapper("操作成功！");
        }
        return JsonWrapper.failureWrapperMsg("提现处理失败，请稍后重试！");
    }

    /**
     * 当前公司钱包余额.
     * @param session session
     * @return
     */
    @RequestMapping("getWalletMoney")
    @ResponseBody
    public HashMap<String,Object> getWalletMoney(HttpSession session){
        User user=(User)session.getAttribute("userInfo");
        return ztcWithdrawalsApplyManager.getWalletMoney(user);
    }


    /**
     * 获取所有待处理提现列表.
     * @return
     */
    @RequestMapping("getAllWillOfZtcWithdrawalsApply")
    @ResponseBody
    public  HashMap<String,Object> getAllWillOfZtcWithdrawalsApply(@RequestParam(defaultValue = "10") Integer pageSize, @RequestParam(defaultValue = "1")Integer pageNumber){
        return ztcWithdrawalsApplyManager.getAllWillOfZtcWithdrawalsApply(pageSize,pageNumber);
    }

    /**
     * 提现记录详情.
     * @param id  提现ID
     * @return
     */
    @RequestMapping("getCashDetail")
    @ResponseBody
    public HashMap<String,Object> getCashDetail(String id){
        ZtcWithdrawalsApply ztcWithdrawalsApply = ztcWithdrawalsApplyManager.get(id);
        if (ztcWithdrawalsApply == null) {
            return JsonWrapper.failureWrapperMsg("提现处理失败，记录不存在！");
        }
        ZtcWallet ztcWallet = ztcWalletManager.findUserWallet(ztcWithdrawalsApply.getBusinessId());
        if (ztcWallet == null) {
            return JsonWrapper.failureWrapperMsg("网络错误，请稍后重试！");
        }
        //可提现金额
        BigDecimal totalMoney = ztcWallet.getTmoney();

        //该业务id（用户，公司）所有未处理的提现记录
        List<ZtcWithdrawalsApply> ztcWithdrawalsApplyList = ztcWithdrawalsApplyManager.findBy("businessId", ztcWithdrawalsApply.getBusinessId(), "status", 1);
        if (ztcWithdrawalsApplyList.size() > 0) {
            for (ZtcWithdrawalsApply z : ztcWithdrawalsApplyList) {
                totalMoney = totalMoney.add(z.getMoney());
            }
        }
        HashMap<String,Object> map=new HashMap<>();
        map.put("id",ztcWithdrawalsApply.getId());
        map.put("businessType",ztcWithdrawalsApply.getBusinessType());
        map.put("money",totalMoney);
        map.put("cashMoney",ztcWithdrawalsApply.getMoney());
        map.put("transferAccountType",ztcWithdrawalsApply.getTransferAccountType());
        map.put("transferAccount",ztcWithdrawalsApply.getTransferAccount());
        map.put("remark",ztcWithdrawalsApply.getFailureDescription());
        map.put("addTime",ztcWithdrawalsApply.getAddTime());
        map.put("handleTime",ztcWithdrawalsApply.getHandleTime());
        User user1=userManager.get(ztcWithdrawalsApply.getFkHandlePerson()==null?"":ztcWithdrawalsApply.getFkHandlePerson());
        map.put("handlePerson",user1==null?"":user1.getAccount());
        map.put("cashStatus",ztcWithdrawalsApply.getStatus());
        if(ztcWithdrawalsApply.getBusinessType()==1){
            AppUser user=  appUserManager.get(ztcWithdrawalsApply.getBusinessId());
            if (user!=null){
                map.put("account",user.getName());
                map.put("realName",user.getRealName());
                map.put("phone",user.getPhone());
                map.put("userCard",user.getUserCard());
                map.put("status",getUserStatus(user.getStatus()));
            }else{
                return JsonWrapper.failureWrapperMsg("用户数据异常！");
            }
        }
        if(ztcWithdrawalsApply.getBusinessType()==2){
            ZtcTransport ztcTransport=ztcTransportManager.get(ztcWithdrawalsApply.getBusinessId());
            if (ztcTransport!=null){
                map.put("cashBodyName",ztcTransport.getFullName());
                map.put("signTel",ztcTransport.getSignTel());
                map.put("status",getZtcTransportStatus(ztcTransport.getStatus()));
                map.put("type",getZtcTransportType(ztcTransport.getType()));
                map.put("address",ztcTransport.getAddress());
                SysArea sysArea=sysAreaManager.findUniqueBy("code",ztcTransport.getAreaCode());
                map.put("area",sysArea==null?"":sysArea.getFullName());
            }else{
                return JsonWrapper.failureWrapperMsg("公司数据异常！");
            }
        }
        return JsonWrapper.successWrapper(map);
    }

     /**用户状态：1正常，2冻结*/
    private String getUserStatus(Integer userStatus){
        if (userStatus==null){
            return null;
        }
        switch (userStatus){
            case 1:return "正常";
            case 2:return "冻结";
            default:return null;
        }
    }

    /**公司状态：1注册未审核，2未通过审核，3已通过审核，4冻结*/
    private String getZtcTransportStatus(Integer ztcTransportStatus){
        if (ztcTransportStatus==null){
            return null;
        }
        switch (ztcTransportStatus){
            case 1:return "未审核";
            case 2:return "未通过审核";
            case 3:return "运营";
            case 4:return "冻结";
            default:return null;
        }
    }

    /**公司类型：0总公司，1省管理公司，2地级市公司，3运营公司，4车方公司*/
    private String getZtcTransportType(Integer ztcTransportType){
        if (ztcTransportType==null){
            return null;
        }
        switch (ztcTransportType){
            case 0:return "平台公司";
            case 1:return "省级公司";
            case 2:return "地级公司";
            case 3:return "运营公司";
            case 4:return "车方公司";
            case 5:return "快递公司";
            default:return null;
        }
    }

    /**
     * 获取当前公司所有提现列表.
     * @return
     */
    @RequestMapping("getAllZtcWithdrawalsApply")
    @ResponseBody
    public  HashMap<String,Object> getAllZtcWithdrawalsApply(HttpSession session,@RequestParam(defaultValue = "10") Integer pageSize, @RequestParam(defaultValue = "1")Integer pageNumber){
        User user=(User)session.getAttribute("userInfo");
        return ztcWithdrawalsApplyManager.getAllZtcWithdrawalsApply(user.getTransportId(),pageSize,pageNumber,ztcTransportManager.get(user.getTransportId()).getType());
    }
}